﻿using System;

using Microsoft.SharePoint;
using Microsoft.SharePoint.Publishing;
using System.Xml;
using Microsoft.SharePoint.Workflow;

namespace ISolutions.WCMTools.Impl
{
    /// <summary>
    /// Static helper class for approval workflows
    /// </summary>
    public static class ApprovalWorkflowHelper
    {
        /// <summary>
        /// Copies the approval workflow settings from one page library to an other
        /// </summary>
        /// <param name="pSource"></param>
        /// <param name="pTarget"></param>
        public static void ApplyApprovalWorkflowConfig(SPWeb pSource, SPWeb pTarget)
        {
            SPList sourcePagesList = pSource.Lists[PublishingWeb.GetPagesListId(pSource)];
            SPList targetPagesList = pTarget.Lists[PublishingWeb.GetPagesListId(pTarget)];

            // Checks if Moderation (= Approval) is enabled
            if (sourcePagesList.EnableModeration)
            {
                SPWorkflowAssociation sourceAssociation = sourcePagesList.WorkflowAssociations[sourcePagesList.DefaultContentApprovalWorkflowId];
                SPWorkflowAssociation targetAssociation = targetPagesList.WorkflowAssociations[targetPagesList.DefaultContentApprovalWorkflowId];

                targetAssociation.AssociationData = sourceAssociation.AssociationData;
                targetPagesList.UpdateWorkflowAssociation(targetAssociation);            
            }
            else
            {
                targetPagesList.EnableModeration = false;
                targetPagesList.Update();
            }
        }
    }
}